#include "getMessagesCommand.h"

QDomDocument GetMessagesCommand::run(QDomDocument doc) {
    QDomDocument xmlDocument;
    QString result;

    if (this->isAuthorized(doc)) {
        User* me = this->getCurrentUser(doc);
        QDomNodeList roomNodes = doc.elementsByTagName("room");
        if (roomNodes.count() == 1) {
            QString roomName = roomNodes.at(0).toElement().text().trimmed();
            Room* room = DB::getInstance()->findRoom(roomName);
            result = this->process(me, room);
        } else {
            result = "<getMessages><success>FALSE</success><reason>WRONG_XML</reason></getMessages>";
        }
    } else {
        result = "<getMessages><success>FALSE</success><reason>NOT_AUTHORIZED</reason></getMessages>";
    }

    xmlDocument.setContent(result);
    return xmlDocument;
}

QString GetMessagesCommand::process(User* me, Room* room) {
    QString result;
    if (room == NULL) {
        result = "<getMessages><success>FALSE</success><reason>NO_SUCH_ROOM</reason></getMessages>";
    } else {
        if (room->isMember(me)) {
            result = "<getMessages><success>TRUE</success>";
            QList<Message*> messages = room->getMessages(0);
            for (int i = 0; i < messages.size(); i++) {
                result.append("<message><date>")
                    .append( QString::number( messages.at(i)->getDateTime().toTime_t() ))
                    .append("</date><user>")
                    .append( messages.at(i)->getUser()->getLogin() )
                    .append("</user><text>")
                    .append( messages.at(i)->getText() )
                    .append("</text></message>");
            }
            result.append("</getMessages>");
        } else {
           result = "<getMessages><success>FALSE</success><reason>YOU_ARE_NOT_IN_ROOM</reason></getMessages>";
        }
    }
    return result;
}
